package cn.wpy.web;

import cn.wpy.service.AIService;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class AIController {

    private final AIService aiService;

    @Value("${spring.cloud.ai.apikey}")
    private String apiKey;

    @Value("${spring.cloud.ai.apiurl}")
    private String apiUrl;

    @PostMapping("/chat")
    public SseEmitter chat(@RequestBody String messageContent) {
        SseEmitter emitter = new SseEmitter();
        List<Message> messages = new ArrayList<>();
        messages.add(Message.builder().role(Role.SYSTEM.getValue()).content("你是一位有帮助的助手").build());
        messages.add(Message.builder().role(Role.USER.getValue()).content(messageContent).build());

        new Thread(() -> {
            try {
                aiService.streamCallWithCallback(messages, content -> {
                    try {
                        emitter.send(SseEmitter.event().data(content));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
                emitter.complete();
            } catch (Exception e) {
                e.printStackTrace();
                emitter.completeWithError(e);
            }
        }).start();

        return emitter;
    }
}